import { type ReactNode } from 'react';
import SubmenuNav, {
  type ISubmenuNavItem,
} from '@/app/[locale]/admin/common/submenu/submenu-nav';
import SubmenuContent from '@/app/[locale]/admin/common/submenu/submenu-content';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { clientQueryAllMenu, queryPath } from '@/services/api';
import type { IMenu, IPath } from '@/interfaces';
import { getTranslator } from 'next-intl/server';
import Link from 'next/link';

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryAllMenu({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      path: resp1.data as IPath,
      menus: resp2.data as IMenu[],
    };
  } catch (e) {
    return {
      isSuccess: false,
    };
  }
}

export default async function DashboardLayout({
  children,
  params: { locale },
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  const data = await getData();

  if (data.isSuccess) {
    const t = await getTranslator(locale);

    const items: ISubmenuNavItem[] = [
      {
        path: '/admin/log/nginx',
        name: t('logAdminPage.accessLog'),
        icon: 'bi-view-list',
      },
      {
        path: '/admin/log/nginx/nginx-error',
        name: t('logAdminPage.errorLog'),
        icon: 'bi-bug',
      },
      {
        path: '/admin/log/nginx/nginx-config-scheduler',
        name: t('logAdminPage.configScheduler'),
        icon: 'bi-clock',
      },
      {
        path: '/admin/log/nginx/nginx-config-key',
        name: t('logAdminPage.configKey'),
        icon: 'bi-shield-lock',
      },
    ];

    return (
      <div>
        <SubmenuNav items={items} />
        <SubmenuContent type="log">{children}</SubmenuContent>
        <div className="my-4 small">
          <i className="bi bi-info-circle me-2"></i>
          <Link
            target="_blank"
            rel="noreferrer"
            href="https://www.youdeyiwu.com/docs/docs/nginx-access-help"
            className="text-secondary link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
          >
            {t('logAdminPage.nginxLogAccessHelp')}
          </Link>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
